<template>
	<div class="page" v-loading="loading">
		<div class="title"> 部门：CNC加工中心 </div>
		<div class="content">
			<div class="content_item">
				<div class="con_item_t">
					<div class="form">
						<el-form>
							<el-form-item class="lable" label="制作人编号：">
								<el-input v-model="form.employeeNumber" placeholder="" @keydown.enter="handleEmployee"></el-input>
							</el-form-item>
							<el-form-item class="lable" label="制作人姓名：">
								<el-input v-model="form.employeeName" placeholder=""></el-input>
							</el-form-item>
							<el-form-item class="lable" label="生产批号：">
								<el-input ref="productionBatchNumberRef" v-model="form.productionBatchNumber" placeholder="" @keydown.enter="handleProductionBatchNumber" @change="handleProductionBatchNumber"></el-input>
							</el-form-item>
							<el-form-item class="lable" label="盒号：">
								<el-input v-model="form.boxNumber" placeholder="" @keydown.enter="handleBoxNumber" @change="handleBoxNumber"></el-input>
							</el-form-item>
							<el-form-item class="lable" label="排版号：">
								<el-input v-model="form.printingNumber" placeholder=""></el-input>
							</el-form-item>
						</el-form>
						<div class="btn">
							<el-button type="" @click="router.go(-1)">取消</el-button>
							<el-button type="primary" @click="handleReceive">接收</el-button>
							<el-button type="success" @click="handleComplete">完成</el-button>
						</div>
					</div>
					<div class="process">
						<div class="title">工序</div>
						<div class="process_list">
							<el-checkbox-group v-model="processListValue" v-if="processList.length > 0">
								<div v-for="(item, index) in processList" :key="item.id">
									<el-checkbox :label="item.title" :value="{ id: item.id, title: item.title }" />
								</div>
							</el-checkbox-group>
							<el-empty v-else description="暂无数据" :image-size="100" />
						</div>
					</div>
					<div class="materialName">
						<div class="title">材料名称/编号</div>
						<div class="process_list">
							<el-checkbox-group v-model="materialNameListValue" v-if="materialNameList.length > 0">
								<div v-for="(item, index) in materialNameList" :key="item.id">
									<el-checkbox :label="item.title" :value="{ id: item.id, title: item.title }" />
								</div>
							</el-checkbox-group>
							<el-empty v-else description="暂无数据" :image-size="100" />
						</div>
					</div>
					<div class="deviceName">
						<div class="title">设备名称/编号</div>
						<div class="process_list">
							<el-checkbox-group v-model="deviceNameListValue" v-if="deviceNameList.length > 0">
								<div v-for="(item, index) in deviceNameList" :key="item.id">
									<el-checkbox :label="item.device_name" :value="{ id: item.id, title: item.device_name }" />
								</div>
							</el-checkbox-group>
							<el-empty v-else description="暂无数据" :image-size="100" />
						</div>
					</div>
				</div>
				<div class="con_item_b">
					<div class="title">订单详情显示栏</div>
					<el-table style="width: 100%" :data="orderInfo.items">
						<el-table-column prop="prop" label="订单号" width="width">{{ orderInfo.order_sn }} </el-table-column>
						<el-table-column prop="prop" label="盒号" width="width"> {{ orderInfo.box_num }}</el-table-column>
						<el-table-column prop="product.title" label="产品名称" width="width"> </el-table-column>
						<!-- <el-table-column prop="prop" label="规格型号" width="width"> </el-table-column> -->
						<el-table-column prop="prop" label="医生" width="width">{{ orderInfo.docuser?.nickname }} </el-table-column>
						<el-table-column prop="prop" label="患者" width="width">{{ orderInfo.name }} </el-table-column>
						<el-table-column prop="prop" label="牙位" width="150">
							<template #default="scope">
								<tooth1 :single_crown="scope.row.single_crown_text" :multiple_crown="scope.row.multiple_crown"></tooth1>
							</template>
						</el-table-column>
						<el-table-column prop="yase_remark" label="牙色" width="width"> </el-table-column>
						<el-table-column prop="num" label="数量" width="60"> </el-table-column>
						<el-table-column prop="prop" label="材料批号" width="150" fixed="right">
							<template #default="scope">
								<el-input v-model="scope.row.material_num" placeholder="" @keydown.enter="handleMaterialNum(scope.row)"></el-input>
							</template>
						</el-table-column>
						<el-table-column prop="device_code" label="设备编码" width="150" fixed="right"> </el-table-column>
						<el-table-column prop="material_equipment_code" label="材料/设备名称" width="150" fixed="right"> </el-table-column>
						<el-table-column prop="prop" label="排版号" width="150" fixed="right">
							<template #default="scope">
								<el-input v-model="scope.row.typesetting_num" placeholder="" @keydown.enter="handleTypesettingNum(scope.row)"></el-input>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<div class="content_item">
				<div class="title">订单完成情况显示栏</div>
				<el-table style="width: 100%" :data="completeList" :height="completeList.length > 0 ? '95%' : '100'">
					<el-table-column prop="department.name" label="部门" width="width"> </el-table-column>
					<el-table-column prop="process" label="工序" width="width">
						<template #default="scope">
							<div v-for="item in scope.row.process" :key="item.id">{{ item.title }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="admin.nickname" label="员工" width="width"> </el-table-column>
					<el-table-column prop="prop" label="完成时间" width="width">
						<template #default="scope">
							<div>{{ formatTimestamp(scope.row.createtime) }}</div>
						</template>
					</el-table-column>
					<el-table-column prop="status" label="状态" width="width">
						<template #default="scope">
							<div v-if="scope.row.status == 1">未做</div>
							<div v-else>完成</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
	</div>
</template>
<script setup>
	import { ref, onMounted, nextTick } from 'vue';
	import { get_admin_info, add_cnc_to_patient_item, add_cnc_info, get_cnc_lists } from '@/api/MachiningCenter/index';
	import { getOrderDetail } from '@/api/PlaceOrder/index';
	import { ElMessage } from 'element-plus';
	import { useRoute, useRouter } from 'vue-router';
	import { formatTimestamp } from '@/utils/formatTime';
	const ruote = useRoute();
	const router = useRouter();
	//loading
	const loading = ref(false);

	//form表单数据
	const form = ref({
		employeeNumber: '', //员工编号
		employeeName: '', //制作人姓名
		productionBatchNumber: '', //生产批号
		boxNumber: '', //盒号
		printingNumber: '' //排版号
	});

	// 生产批号输入框引用
	const productionBatchNumberRef = ref(null);

	//工序数据
	const processList = ref([]);

	//工序选中结果
	const processListValue = ref([]);

	//材料名称数据
	const materialNameList = ref([]);

	//材料名称选中结果
	const materialNameListValue = ref([]);

	//设备名称数据
	const deviceNameList = ref([]);

	//设备名称选中结果
	const deviceNameListValue = ref([]);

	//订单信息
	const orderInfo = ref({});

	//员工信息
	const userInfo = ref({});

	//完成情况加载列表
	const completeList = ref([]);

	//获取cnc加工完成情况
	const getCncComplete = async () => {
		try {
			const res = await get_cnc_lists({
				patient_id: orderInfo.value.id
			});
			completeList.value = res.data;
		} catch (err) {}
	};

	//完成按钮点击事件
	const handleComplete = async () => {
		//如果没有选择值 提示
		if (processListValue.value.length == 0 || materialNameListValue.value.length == 0 || deviceNameListValue.value.length == 0) {
			ElMessage.warning('请选择工序/材料名称/设备名称');
			return;
		}
		//如果没有订单信息 提示
		if (!orderInfo.value.items) {
			ElMessage.warning('请添加订单信息');
			return;
		}

		loading.value = true;

		//循环订单信息的产品
		orderInfo.value.items.forEach(async (item) => {
			//赋值设备编码
			item.device_code = deviceNameListValue.value.map((item) => item.title);
			//赋值材料/设备名称
			item.material_equipment_code = materialNameListValue.value.map((item) => item.title);
			//添加参数到订单信息
			await addParams('', '', item.device_code.join(','), item.material_equipment_code.join(','), item.id);
		});

		//添加信息到日志 未作状态
		await handleAddToLog(processListValue.value.map((item) => item.id).join(','), 2);

		loading.value = false;
	};

	//接收按钮点击事件
	const handleReceive = async () => {
		//如果没有选择值 提示
		if (processListValue.value.length == 0 || materialNameListValue.value.length == 0 || deviceNameListValue.value.length == 0) {
			ElMessage.warning('请选择工序/材料名称/设备名称');
			return;
		}
		//如果没有订单信息 提示
		if (!orderInfo.value.items) {
			ElMessage.warning('请添加订单信息');
			return;
		}

		loading.value = true;

		//循环订单信息的产品
		orderInfo.value.items.forEach(async (item) => {
			//赋值设备编码
			item.device_code = deviceNameListValue.value.map((item) => item.title);
			//赋值材料/设备名称
			item.material_equipment_code = materialNameListValue.value.map((item) => item.title);
			//添加参数到订单信息
			await addParams('', '', item.device_code.join(','), item.material_equipment_code.join(','), item.id);
		});

		//添加信息到日志 未作状态
		await handleAddToLog(processListValue.value.map((item) => item.id).join(','), 1);

		loading.value = false;
	};

	/**
	 * 添加cnc加工完成情况到操作日志
	 *@param {string} product_process_id 工序id
	 *@param {string} status 状态 1未作 2完成
	 */
	const handleAddToLog = async (product_process_id, status) => {
		try {
			const res = await add_cnc_info({
				admin_id: userInfo.value.id, //操作人id
				patient_id: orderInfo.value.id, // 订单id
				department_id: userInfo.value.department_id, //操作人部门
				product_process_id: product_process_id,
				status: status
			});
			if (res) {
				ElMessage.success(res.msg);
			}

			//获取订单完成列表
			getCncComplete();
		} catch (err) {}
	};

	//排版号回车事件
	const handleTypesettingNum = async (row) => {
		//如果输入框为空 提示
		if (row.typesetting_num == '') {
			ElMessage.warning('请输入排版号');
			return;
		}
		//添加参数到订单信息
		await addParams('', row.typesetting_num, '', '', row.id);
	};

	//材料批号回车事件
	const handleMaterialNum = async (row) => {
		//如果输入框为空 提示
		if (row.material_num == '') {
			ElMessage.warning('请输入材料批号');
			return;
		}
		//添加参数到订单信息
		await addParams(row.material_num, '', '', '', row.id);
	};

	/**
	 * 添加参数到订单信息
	 * @param material_num  材料批号
	 * @param typesetting_num 排版号
	 * @param device_code 设备编码
	 * @param material_equipment_code 材料/设备编码
	 * @param patient_item_id  订单信息产品id
	 */
	const addParams = async (material_num, typesetting_num, device_code, material_equipment_code, patient_item_id) => {
		try {
			await add_cnc_to_patient_item({
				material_num,
				typesetting_num,
				device_code,
				material_equipment_code,
				patient_item_id
			});
		} catch (err) {
			ElMessage.error(err.message);
		}
	};

	/**
	 * 查询订单信息
	 * @param params 查询参数
	 */
	const getOrderInfo = async (params) => {
		//根据生产批号查询订单信息
		loading.value = true;
		let res = await getOrderDetail(params);
		loading.value = false;
		if (res.data) {
			//给每个产品添加字段
			res.data.items.forEach((item) => {
				item.material_num = ''; //材料批号
				item.typesetting_num = ''; //排版号
				item.device_code = ''; //设备编码
				item.material_equipment_code = ''; //材料/设备编码
			});
			orderInfo.value = res.data;

			//清空工序列表
			processListValue.value = [];
			//清空材料名称列表
			materialNameListValue.value = [];
			//清空设备名称列表
			deviceNameListValue.value = [];

			//获取订单完成列表
			getCncComplete();
		}
	};

	//盒号输入框回车事件
	const handleBoxNumber = async (e) => {
		//如果没值 不操作
		if (!form.value.boxNumber) {
			ElMessage.warning('请输入盒号');
			return;
		}
		//如果生产批号有值 清空
		if (form.value.productionBatchNumber) {
			form.value.productionBatchNumber = '';
		}
		//处理查询参数
		const params = {
			box_num: form.value.boxNumber
		};
		//查询订单信息
		getOrderInfo(params);
	};

	//生产批号输入框回车事件
	const handleProductionBatchNumber = async (e) => {
		//如果没值 不操作
		if (!form.value.productionBatchNumber) {
			ElMessage.warning('请输入生产批号');
			return;
		}
		//如果盒号有值 清空
		if (form.value.boxNumber) {
			form.value.boxNumber = '';
		}
		//处理查询参数
		const params = {
			order_sn: form.value.productionBatchNumber
		};
		//查询订单信息
		getOrderInfo(params);
	};

	//员工输入框回车事件
	const handleEmployee = async (e) => {
		try {
			//根据员工编号查询信息
			loading.value = true;
			let res = await get_admin_info({
				admin_num: form.value.employeeNumber
			});
			loading.value = false;
			if (res.data) {
				//赋值制作人姓名
				form.value.employeeName = res.data.nickname;
				//赋值工序数据
				processList.value = res.data.process_list;
				//赋值材料名称数据
				materialNameList.value = res.data.department_goods_list;
				//赋值设备名称数据
				deviceNameList.value = res.data.fixed_assets_list;
			}

			userInfo.value = res.data;

			// 聚焦到生产批号输入框
			nextTick(() => {
				if (productionBatchNumberRef.value && productionBatchNumberRef.value.focus) {
					productionBatchNumberRef.value.focus();
				} else if (productionBatchNumberRef.value && productionBatchNumberRef.value.$el) {
					// 如果是Element UI组件，可能需要访问$el
					const input = productionBatchNumberRef.value.$el.querySelector('input');
					if (input) {
						input.focus();
					}
				}
			});
		} catch (err) {
			loading.value = false;
		}
	};

	onMounted(async () => {
		//默认鼠标选中在第一个输入框上
		nextTick(() => {
			document.querySelector('.el-input__inner').focus();
		});
	});
</script>
<style lang="scss" scoped>
	.page {
		width: 100%;
		min-height: 100vh;
		background-color: #fff;
		padding: 20px;
		box-sizing: border-box;
		.title {
			font-size: 16px;
			font-weight: 700;
			color: #333;
			margin-bottom: 10px;
		}

		.content {
			width: 100%;
			display: flex;
			justify-content: space-between;

			.content_item {
				height: calc(100vh - 80px);
			}
			.content_item:nth-child(1) {
				width: 70%;
				.con_item_t {
					display: flex;
					justify-content: space-between;
					.form {
						width: 300px;
						height: 290px;

						:deep(.el-form-item__label) {
							width: 100px;
						}

						.btn {
							display: flex;
							align-items: center;
							justify-content: space-around;

							.el-button {
								width: 120px;
							}
						}
					}

					.process,
					.materialName,
					.deviceName {
						width: 250px;
						height: 290px;

						.process_list {
							border: 1px solid #dcdfe6;
							height: calc(100% - 40px);
							overflow-y: auto;
							padding: 0 10px;
						}
					}
				}

				.con_item_b {
					width: 100%;
					height: calc(100% - 300px);
					margin-top: 10px;
				}
			}

			.content_item:nth-child(2) {
				width: 30%;
				margin-left: 20px;
			}
		}
	}

	:deep(.el-table .el-table__header th) {
		background-color: #f5f7fa !important; /* 设置表头背景色 */
	}
	:deep(.el-checkbox__label) {
		white-space: pre-line !important;
	}
</style>
